#include "initwidget.h"
#include "ui_initwidget.h"
#include <QFileDialog>
#include "ResourceManger/filemanager.h"
#include "editorwindow.h"
InitWidget::InitWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::InitWidget)
{
    ui->setupUi(this);
    this->setFixedSize(800,600);
    this->setWindowTitle("MyGame");
    this->setWindowIcon(QIcon(":/res/icon/myGame.png"));

    connect(ui->YesBtn,&QPushButton::clicked,this,[=](){
        InitApplication();
    });
    connect(ui->NewChooseDir,&QPushButton::clicked,this,[=](){
        QString path = ChooseDir();
        if(!path.isEmpty())
        {
            ui->NewDirLineEdit->setText(path);
        }
    });
    connect(ui->OpenChooseDir,&QPushButton::clicked,this,[=](){
        QString path = ChooseDir();
        if(!path.isEmpty())
        {
            ui->OpenDirLineEdit->setText(path);
        }
    });
}

InitWidget::~InitWidget()
{
    delete ui;
}

void InitWidget::InitApplication()
{
    QDir dir;
    //新建项目
    if(ui->tabWidget->currentIndex() == 0)
    {
        QString rootDir = ui->NewDirLineEdit->text();

        if(!dir.exists(rootDir))
        {
            EventCenter::Instance().Warning(rootDir + "\n该文件夹不存在！\n请重新选择！");
            return;
        }
        QString newDir = rootDir + "/" +ui->nameEdit->text();
        if(dir.exists(newDir))
        {
            EventCenter::Instance().Warning("文件夹中存在同名项目，\n请重新命名！");
            return;
        }
        if(!dir.mkdir(newDir + "/"))
        {
            EventCenter::Instance().Warning("创建文件夹失败！\n请检查目录访问权限:\n" + newDir);
        }
        FileManager::Instance().SetRootPath(newDir);
        QDir::setCurrent(FileManager::Instance().GetRootPath());
        qDebug()<<__FILE__<<__LINE__<<"设置工作目录"<<FileManager::Instance().GetRootPath();
        //检查是否填写完整
        if(ui->nameEdit->text().length() <= 0)
        {
            EventCenter::Instance().Warning("项目名称非法！\n请重新命名！");
        }
        GameManager::Instance().name = ui->nameEdit->text();
        EditorWindow::Instance().showMaximized();
        this->close();
    }
    else
    {
        //TODO打开旧项目
        if(!dir.exists(ui->OpenDirLineEdit->text()))
        {
            EventCenter::Instance().Warning("项目不存在");
        }
        else
        {
            FileManager::Instance().SetRootPath(ui->OpenDirLineEdit->text());
            QDir::setCurrent(FileManager::Instance().GetRootPath());
            qDebug()<<__FILE__<<__LINE__<<"设置工作目录"<<FileManager::Instance().GetRootPath();
            EditorWindow::Instance().showMaximized();
            this->close();
        }
    }

}

QString InitWidget::ChooseDir()
{
    QString path = QFileDialog::getExistingDirectory(this, "选择路径...", "./");
    if(path.isEmpty())
    {
        qDebug()<<"选择路径失败!";
    }
    return path;
}
